package com.yiyw.herostory.pipeline.outBound;

import com.google.protobuf.GeneratedMessageV3;
import com.yiyw.herostory.factory.GameMsgProtocolFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import lombok.extern.slf4j.Slf4j;

/**
 * @Author yiyw
 * @Description 消息编码器
 * @Date 2022/8/13 18:16
 **/
@Slf4j
public class GameMsgEncoder extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (msg instanceof GeneratedMessageV3) {
            log.info("返回客户端的消息,\n 消息类型: {}, 消息内容: {}", msg.getClass().toString(), msg);
            // 获取消息类型
            int msgCode = GameMsgProtocolFactory.getMsgCodeByGameProtocol(msg);

            // 进行编码
            byte[] bytes = ((GeneratedMessageV3) msg).toByteArray();
            ByteBuf byteBuf = ctx.alloc().buffer();
            byteBuf.writeShort((short) 0); // 写出消息长度，只是为了占位
            byteBuf.writeShort((short) msgCode); // 写出消息内容
            byteBuf.writeBytes(bytes); // 写出消息内容

            // 转型
            BinaryWebSocketFrame frame = new BinaryWebSocketFrame(byteBuf);
            super.write(ctx, frame, promise);
            return;
        }
        super.write(ctx, msg, promise);
    }
}
